﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WG计划管理工具
{
    public partial class frmPPSelector : Form
    {
        public bool bCancel = true ;
        public DataTable dtReturn;
        public List<DataForReturn> dfrlst;
        //默认数量查询语句(无单项备注)
        string tab1_strDefaultSelectString1 = "select jhb005 型号规格,sum(jhb008-jhb013) 订单数量 from scjhb_table,scjha_table,htb_table where jha007='Y' and jhb013<jhb008 and jhb001=jha001 and htb001=jhb003 and htb002=jhb004 and (htb023 is null or len(ltrim(htb023))=0) and (select count(*) from wgjhht where 生产计划号=jhb001 and 生产计划项次=jhb002)=0 and scjhb_table.bChecked=0";
        //默认数量查询语句(有单项备注)
        string tab2_strDefaultSelectString1 = "select jhb024 合同号,jhb001 生产计划号,jhb002 生产计划项次,jhb005 型号规格,jhb008-jhb013 生产计划数量,htb023 单项备注,htc002 合同备注 from scjhb_table,scjha_table,htb_table,htc_table where jha007='Y' and jhb013<jhb008 and jhb001=jha001 and htb001=jhb003 and htb002=jhb004 and htb001=htc001 and htb023 is not null and len(ltrim(htb023))>0 and (select count(*) from wgjhht where 生产计划号=jhb001 and 生产计划项次=jhb002)=0 and scjhb_table.bChecked=0";
        //默认计划查询语句
        string tab1_strDefaultSelectString2 = "select jhb024 合同号,jhb001 计划编号,jhb002 计划项次,jhb005 型号规格,jhb008 订单数量,jhb009 交货期,jhb013 已出库数量 from scjhb_table,scjha_table where jha007='Y' and jhb013<jhb008 and jhb001=jha001 and (select count(*) from wgjhht where 生产计划号=jhb001 and 生产计划项次=jhb002)=0 and bChecked=0 and jhb005='@型号规格'";
        //查询生产计划号
        string strDefaultSelectString3 = "select jhb024 合同号,jhb001 生产计划号,jhb002 生产计划项次,jhb008-jhb013 生产计划数量 from scjhb_table,scjha_table where jha007='Y' and jhb013<jhb008 and jhb001=jha001 and (select count(*) from wgjhht where 生产计划号=jhb001 and 生产计划项次=jhb002)=0 and bChecked=0 and jhb005='@型号规格'";
        //查询工序结余
        string strJYSelectString = "select sum(gxjy008-gd035) from gxjy_table ,gd_table where gxjy001=gd001 and gxjy004='@型号规格' and @工序";
        //查询外购库结余
        string strWGJYSelectString = "select sum(数量) from wgjy where 型号规格='@型号规格'";
        //更新生产计划表检查标记
        string strUpdateCheckMark = "update scjhb_table set bChecked=@标记 where jhb001='@计划编号' and jhb002='@计划项次'";

        public struct DataForReturn
        {
            public string strModel;             //型号规格
            public string[] strPPNo;               //生产计划号
            public string[] strPX;                    //生产计划项次
            public string[] strContract;          //合同号
            public int[] iQuantity;                  //生产计划数量
            public int iSum;                          //生产计划总数
            public string strMemo;             //备注
        }

        public frmPPSelector()
        {
            InitializeComponent();
        }

        private int GetInt(object tmpobj)
        {
            int r = 0;
            try
            {
                r= Convert.ToInt32(tmpobj);
            }
            catch
            {
                r= 0;
            }
            if (r < 0)
            {
                r = 0;
            }
            return r;
        }

        private string GetString(object tmpobj)
        {
            try
            {
                return tmpobj.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string strTmpSelectString1 = tab1_strDefaultSelectString1;
            string strTmpSelectString2 = tab2_strDefaultSelectString1;
            SqlTools.SqlTools sqt = new SqlTools.SqlTools(WG计划管理工具.Properties.Settings.Default.ConnectionString);
            if (txtContractNo.Text.Trim().Length > 0)
            {
                strTmpSelectString1 += " and jhb024 like '" + txtContractNo.Text.Trim() + "'";
                strTmpSelectString2 += " and jhb024 like '" + txtContractNo.Text.Trim() + "'";
            }
            if (txtModel.Text.Trim().Length > 0)
            {
                strTmpSelectString1 += " and jhb005 like '" + txtModel.Text.Trim() + "'";
                strTmpSelectString2 += " and jhb005 like '" + txtModel.Text.Trim() + "'";
            }
            if (txtPPNo.Text.Trim().Length > 0)
            {
                strTmpSelectString1 += " and jhb001 like '" + txtPPNo.Text.Trim() + "'";
                strTmpSelectString2 += " and jhb001 like '" + txtPPNo.Text.Trim() + "'";
            }
            strTmpSelectString1 += " group by jhb005 order by jhb005";
            strTmpSelectString2 += " order by jhb005";
            DataTable tmpdt1 = sqt.GetDataTable(strTmpSelectString1);
            tmpdt1.Columns.Add("成品库存");
            tmpdt1.Columns.Add("半成品库存");
            tmpdt1.Columns.Add("在制品");
            tmpdt1.Columns.Add("外购库");
            DataTable tmpdt2 = sqt.GetDataTable(strTmpSelectString2);
            tmpdt2.Columns.Add("成品库存");
            tmpdt2.Columns.Add("半成品库存");
            tmpdt2.Columns.Add("在制品");
            tmpdt2.Columns.Add("外购库");

            if (tmpdt1.Rows.Count+tmpdt2.Rows.Count  > 300)
            {
                DialogResult dr = MessageBox.Show("查询记录为" + Convert.ToString (tmpdt1 .Rows.Count +tmpdt2.Rows.Count ) + "条，查询耗时可能会较长，点击取消添加查询部分条件后可提高查询速度！点击确定继续查询！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (dr == DialogResult.Cancel)
                {
                    txtContractNo.Focus();
                    return;
                }
            }
            int iCount=tmpdt1.Rows.Count + tmpdt2.Rows.Count;
            if (iCount ==0)
            {
                tab1_dgv1.DataSource = null;
                tab1_dgv2.DataSource = null;
                tab2_dgv1.DataSource = null;
                return ;
            }
            QueryData1(tmpdt1);
            QueryData2(tmpdt2);
            tab1_dgv1.DataSource = tmpdt1;
            tab1_dgv1.AutoResizeColumns();
            tab2_dgv1.DataSource = tmpdt2;
            tab2_dgv1.AutoResizeColumns();
            if (tmpdt2.Rows.Count > 0)
            {
                tab2.Text = "有单项备注*";
            }
            else
            {
                tab2.Text = "有单项备注";
            }
            txtAllCount.Text = tab1_dgv1.Rows.Count.ToString();
        }

        private void QueryData1(object tmpobj)      //无单项备注
        {
            DataTable tmpdt = (DataTable)tmpobj;
            tsProgressBar1.Value = 0;
            tsProgressBar1.Maximum = 100;
            tslblProgress.Text = string.Empty;
            SendMessageFromThread.SetProgressFromThread spft = new SendMessageFromThread.SetProgressFromThread(tsProgressBar1 );
            SendMessageFromThread.SetTextFromThread stft = new SendMessageFromThread.SetTextFromThread (tslblProgress);
            SqlTools.SqlTools sqt = new SqlTools.SqlTools(WG计划管理工具.Properties.Settings.Default.ConnectionString);
            for (int i = tmpdt.Rows.Count - 1; i >= 0; i--)
            {
                //成品库存
                tmpdt.Rows[i]["成品库存"] = GetInt(sqt.DoCmdScalarData(strJYSelectString.Replace("@工序", "gxjy007='成品库'")
                                                                                                                                                    .Replace("@型号规格", GetString(tmpdt.Rows[i]["型号规格"]))));
                //半成品库存
                tmpdt.Rows[i]["半成品库存"] = GetInt(sqt.DoCmdScalarData(strJYSelectString.Replace("@工序", "gxjy007='半成品库'")
                                                                                                                                                    .Replace("@型号规格", GetString(tmpdt.Rows[i]["型号规格"]))));
                //在制品
                tmpdt.Rows[i]["在制品"] = GetInt(sqt.DoCmdScalarData(strJYSelectString.Replace("@工序", "(gxjy007<>'成品库' and gxjy007<>'半成品库')")
                                                                                                                                                    .Replace("@型号规格", GetString(tmpdt.Rows[i]["型号规格"]))));
                //外购库
                tmpdt.Rows[i]["外购库"] = GetInt(sqt.DoCmdScalarData(strWGJYSelectString.Replace("@型号规格", GetString(tmpdt.Rows[i]["型号规格"]))));
                spft.SetProgress((int)((tmpdt.Rows.Count - i) * 100 / tmpdt.Rows.Count));
                stft.SetText(Convert.ToString(tmpdt.Rows.Count - i) + "//" + tmpdt.Rows.Count.ToString());
                Application.DoEvents();
                if ((GetInt(tmpdt.Rows[i]["订单数量"]) - GetInt(tmpdt.Rows[i]["成品库存"]) - GetInt(tmpdt.Rows[i]["半成品库存"]) - GetInt(tmpdt.Rows[i]["在制品"]) - GetInt(tmpdt.Rows[i]["外购库"])) <= 0)
                {
                    tmpdt.Rows.RemoveAt(i);
                }
            }
        }

        private void QueryData2(object tmpobj)      //有单项备注
        {
            DataTable tmpdt = (DataTable)tmpobj;
            tsProgressBar1.Value = 0;
            tsProgressBar1.Maximum = 100;
            tslblProgress.Text = string.Empty;
            SendMessageFromThread.SetProgressFromThread spft = new SendMessageFromThread.SetProgressFromThread(tsProgressBar1);
            SendMessageFromThread.SetTextFromThread stft = new SendMessageFromThread.SetTextFromThread(tslblProgress);
            SqlTools.SqlTools sqt = new SqlTools.SqlTools(WG计划管理工具.Properties.Settings.Default.ConnectionString);
            for (int i = 0; i < tmpdt.Rows.Count; i++)
            {
                //成品库存
                tmpdt.Rows[i]["成品库存"] = GetInt(sqt.DoCmdScalarData(strJYSelectString.Replace("@工序", "gxjy007='成品库'")
                                                                                                                                                    .Replace("@型号规格", GetString(tmpdt.Rows[i]["型号规格"]))));
                //半成品库存
                tmpdt.Rows[i]["半成品库存"] = GetInt(sqt.DoCmdScalarData(strJYSelectString.Replace("@工序", "gxjy007='半成品库'")
                                                                                                                                                    .Replace("@型号规格", GetString(tmpdt.Rows[i]["型号规格"]))));
                //在制品
                tmpdt.Rows[i]["在制品"] = GetInt(sqt.DoCmdScalarData(strJYSelectString.Replace("@工序", "(gxjy007<>'成品库' and gxjy007<>'半成品库')")
                                                                                                                                                    .Replace("@型号规格", GetString(tmpdt.Rows[i]["型号规格"]))));
                //外购库
                tmpdt.Rows[i]["外购库"] = GetInt(sqt.DoCmdScalarData(strWGJYSelectString.Replace("@型号规格", GetString(tmpdt.Rows[i]["型号规格"]))));
                spft.SetProgress((int)((i+1) * 100 / tmpdt.Rows.Count));
                stft.SetText(Convert.ToString(tmpdt.Rows.Count - i) + "//" + tmpdt.Rows.Count.ToString());
                Application.DoEvents();
            }
        }

        private void dgv1_SelectionChanged(object sender, EventArgs e)
        {
            txtSelectedCount.Text = tab1_dgv1.SelectedRows.Count.ToString();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtContractNo.Clear();
            txtPPNo.Clear();
            txtModel.Clear();
            tab1_dgv1.DataSource = null;
            tab1_dgv2.DataSource = null;
            tab2_dgv1.DataSource = null;
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            if (tab1_dgv1.Rows.Count > 0)
            {
                foreach (DataGridViewRow tmpdgvr in tab1_dgv1.Rows)
                {
                    tmpdgvr.Selected = true;
                }
            }
            if (chkImportItemWithMemo.Checked)
            {
                if (tab2_dgv1.Rows.Count > 0)
                {
                    foreach (DataGridViewRow tmpdgvr in tab2_dgv1.Rows)
                    {
                        tmpdgvr.Selected = true;
                    }
                }
            }
        }

        private void 忽略该计划项次ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tab1_dgv1.SelectedRows.Count > 0)
            {
                SqlTools.SqlTools sqt = new SqlTools.SqlTools(WG计划管理工具.Properties.Settings.Default.ConnectionString);
                for (int i = 0; i < tab1_dgv1.SelectedRows.Count; i++)
                {
                    sqt.DoCmdExecuteNonQuery(strUpdateCheckMark.Replace("@计划编号", GetString(tab1_dgv1.SelectedRows[i].Cells["计划编号"].Value))
                                                                                                                   .Replace("@计划项次", GetString(tab1_dgv1.SelectedRows[i].Cells["计划项次"].Value))
                                                                                                                   .Replace ("@标记","1"));
                }
                btnSearch_Click(this, new EventArgs());
            }
        }

        private void dgv1_CurrentCellChanged(object sender, EventArgs e)
        {
            if (tab1_dgv1.CurrentRow != null)
            {
                SqlTools.SqlTools sqt = new SqlTools.SqlTools(WG计划管理工具.Properties.Settings.Default.ConnectionString);
                string strTmpSelectString = tab1_strDefaultSelectString2;
                strTmpSelectString = tab1_strDefaultSelectString2.Replace("@型号规格", GetString(tab1_dgv1.CurrentRow.Cells["型号规格"].Value));
                if (txtContractNo.Text.Trim().Length > 0)
                {
                    strTmpSelectString += " and jhb024 like '" + txtContractNo.Text.Trim() + "'";
                }
                if (txtModel.Text.Trim().Length > 0)
                {
                    strTmpSelectString += " and jhb005 like '" + txtModel.Text.Trim() + "'";
                }
                if (txtPPNo.Text.Trim().Length > 0)
                {
                    strTmpSelectString += " and jhb001 like '" + txtPPNo.Text.Trim() + "'";
                }
                DataTable tmpdt = sqt.GetDataTable(strTmpSelectString );
                tab1_dgv2.DataSource = tmpdt;
                tab1_dgv2.AutoResizeColumns();
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            dfrlst = BuildDataForReturn();
            bCancel = false;
            this.Close();
        }

        private List <DataForReturn > BuildDataForReturn()
        {
            List<DataForReturn> tmpdfrlst = new List<DataForReturn>();
            DataForReturn dfr;
            SqlTools.SqlTools sqt = new SqlTools.SqlTools(WG计划管理工具.Properties.Settings.Default.ConnectionString);
            if (tab1_dgv1.SelectedRows.Count > 0)
            {
                for (int i = 0; i < tab1_dgv1.SelectedRows.Count; i++)
                {
                    dfr = new DataForReturn();
                    dfr.strModel =GetString ( tab1_dgv1.SelectedRows[i].Cells["型号规格"].Value);
                    DataTable tmpdt = sqt.GetDataTable(strDefaultSelectString3.Replace("@型号规格", GetString(tab1_dgv1.SelectedRows[i].Cells["型号规格"].Value)));
                    if (tmpdt.Rows.Count > 0)
                    {
                        dfr.strPPNo = new string[tmpdt.Rows.Count];
                        dfr.strPX = new string[tmpdt.Rows.Count];
                        dfr.iQuantity = new int[tmpdt.Rows.Count];
                        dfr.strContract =new string [tmpdt.Rows.Count ];
                        for (int k = 0; k < tmpdt.Rows.Count; k++)
                        {
                            dfr.strPPNo[k] = GetString(tmpdt.Rows[k]["生产计划号"]);
                            dfr.strPX [k] = GetString(tmpdt.Rows[k]["生产计划项次"]);
                            dfr.iQuantity[k] = GetInt(tmpdt.Rows[k]["生产计划数量"]);
                            dfr.strContract [k]=GetString(tmpdt.Rows [k]["合同号"]);
                        }
                    }
                    dfr.iSum = GetInt(tab1_dgv1.SelectedRows[i].Cells["订单数量"].Value) - GetInt(tab1_dgv1.SelectedRows[i].Cells["成品库存"].Value) - GetInt(tab1_dgv1.SelectedRows[i].Cells["半成品库存"].Value) - GetInt(tab1_dgv1.SelectedRows[i].Cells["在制品"].Value) - GetInt(tab1_dgv1.SelectedRows[i].Cells["外购库"].Value);
                    tmpdfrlst.Add(dfr);
                }
            }

            if (chkImportItemWithMemo.Checked)
            {
                if (tab2_dgv1.SelectedRows.Count > 0)
                {
                    for (int i = 0; i < tab2_dgv1.SelectedRows.Count; i++)
                    {
                        dfr = new DataForReturn();
                        dfr.strModel =GetString ( tab2_dgv1.SelectedRows[i].Cells["型号规格"].Value);
                        dfr.strPPNo = new string[1];
                        dfr.strPX = new string[1];
                        dfr.iQuantity = new int[1];
                        dfr.strContract =new string [1];
                        dfr.strPPNo [0] = GetString(tab2_dgv1.SelectedRows[i].Cells["生产计划号"].Value);
                        dfr.strPX [0] =GetString ( tab2_dgv1.SelectedRows[i].Cells["生产计划项次"].Value);
                        dfr.strContract [0] =GetString ( tab2_dgv1.SelectedRows[i].Cells["合同号"].Value);
                        dfr.iQuantity[0] = GetInt(tab2_dgv1.SelectedRows[i].Cells["生产计划数量"].Value);
                        dfr.iSum = GetInt(tab1_dgv1.SelectedRows[i].Cells["订单数量"].Value) - GetInt(tab1_dgv1.SelectedRows[i].Cells["成品库存"].Value) - GetInt(tab1_dgv1.SelectedRows[i].Cells["半成品库存"].Value) - GetInt(tab1_dgv1.SelectedRows[i].Cells["在制品"].Value) - GetInt(tab1_dgv1.SelectedRows[i].Cells["外购库"].Value);
                        dfr.strMemo = GetString ( tab2_dgv1.SelectedRows[i].Cells["单项备注"].Value);
                        tmpdfrlst.Add(dfr);
                    }
                }
            }
            return tmpdfrlst;
        }
    }
}